package com.ruoyi.common.utils;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * <p>
 * 通过ssh连接服务器
 * @author XiongDa
 * @version 1.0.0
 * @since 2023/11/9 上午 10:32
 **/

public class SshUtils {

    private static final Logger log = LoggerFactory.getLogger(SshUtils.class);

    /**
     * 获取内存  总内存, 已用内存
     */
    private static final String merory = "free -m | fgrep Mem | awk '{print $2 \",\" $3}'";

    /**
     * 获取cpu百分比
     */
    private static final String cpu = "top -n1 -b | fgrep %Cpu | awk '{print $8}'";

    /**
     * 获取磁盘信息    总磁盘, 已用
     */
    private static final String disk = "df -h / | fgrep / | awk '{print $2 \",\" $3}'";

    /**
     * 连接服务器并执行shell命令
     * @param host 主机ip
     * @param port 端口
     * @param userName 用户名
     * @param password 密码
     */
    public static List<String> execCmd(String host, String userName, String password, int port){

        String cmd = merory + "\n" + cpu + "\n" + disk;

        log.info("执行命令: {}", cmd);

        // 创建jsch对象
        JSch jsch = new JSch();
        ChannelExec channelExec=null;
        Session session=null;
        InputStream inputStream=null;

        // 输出结果到字符串数组
        List<String> resultLines = new ArrayList<>();
        HashMap<String, String> resultMap = new HashMap<>();
        // 创建session会话
        try {
            session = jsch.getSession(userName, host, port);
            // 设置密码
            session.setPassword(password);
            // 创建一个session配置类
            Properties sshConfig = new Properties();
            // 跳过公钥检测
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            // 我们还可以设置timeout时间
            session.setTimeout(5000);
            // 建立连接
            session.connect();
            // session建立之后，我们就可以执行shell命令，或者上传下载文件了,下面我来执行shell命令
            channelExec = (ChannelExec) session.openChannel("exec");
            // 将shell传入command
            channelExec.setCommand(cmd);
            // 开始执行
            channelExec.connect();
            // 获取执行结果的输入流
            inputStream = channelExec.getInputStream();
            String result=null;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            while ((result = in.readLine()) != null) {
                resultLines.add(result);
                log.info("命令返回信息：" + result);
            }
        }catch (Exception e){
            log.info("Connect failed, {}" + e.getMessage());
            ArrayList<String> errorMsg = new ArrayList<>();
            errorMsg.add(e.getMessage());
            return errorMsg;
        }finally {
            // 释放资源
            if (channelExec != null) {
                try {
                    channelExec.disconnect();
                } catch (Exception e) {
                    log.info("JSch channel disconnect error: {}" + e);
                }
            }
            if (session!=null){
                try {
                    session.disconnect();
                } catch (Exception e) {
                    log.info("JSch session disconnect error:" + e);
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.info("inputStream close error:" + e);
                }
            }
        }

        return resultLines;
    }




    public static void main(String args[]) {
        String cmd = merory + "\n" + cpu + "\n" + disk;
        List<String> result = execCmd("120.55.72.76", "root", "1937938542zZ", 22);

        System.out.println(result.get(0).split(",")[0]);
        System.out.println(result.get(0).split(",")[1]);

        System.out.println((result.get(1)));
        System.out.println(String.valueOf(100 - Float.parseFloat(result.get(1))));

        System.out.println(result.get(2).split(",")[0]);
        System.out.println(result.get(2).split(",")[1]);


        System.out.println(result);

    }

}
